package com.example.chapter5.controller;

import com.example.chapter5.entity.Blog;
import com.example.chapter5.service.BlogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@CrossOrigin(origins = "http://localhost:5173", allowCredentials = "true", maxAge = 3600)
@RequestMapping("/api")
public class BlogController {
    @Autowired
    private BlogService blogService;

    @GetMapping("/blogs")
    public ResponseEntity<?> getBlogsByPage(
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "10") int size) {
        try {
            List<Blog> blogs = blogService.findBlogsByPage(page, size);
            int count = blogService.countBlogs();
            Map<String,Object> map = new HashMap<>();
            map.put("blogs", blogs);
            map.put("count", count);
            return ResponseEntity.ok(map);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("获取博客列表失败：" + e.getMessage());
        }
    }

    @DeleteMapping("/blogs/{id}")
    public ResponseEntity<?> deleteBlog(@PathVariable("id") int id) {
        try {
            blogService.deleteBlog(id);
            return ResponseEntity.ok().build();
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("删除失败：" + e.getMessage());
        }
    }

    @PutMapping("/blogs/{id}")
    public ResponseEntity<?> updateBlog(@PathVariable("id") int id, @RequestBody Blog blog) {
        try {
            blog.setId(id);
            blogService.updateBlog(blog);
            return ResponseEntity.ok(blog);
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("更新失败：" + e.getMessage());
        }
    }
}
